<template>
  <div class="space-y-6">
    <!-- Header -->
    <div>
      <h1 class="text-2xl font-bold text-gray-900 dark:text-gray-100">对话历史</h1>
      <p class="text-gray-600 dark:text-gray-400 mt-1">
        查看和管理您的AI对话记录与使用统计
      </p>
    </div>

    <!-- Usage Statistics -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- Navigation -->
      <div class="lg:col-span-1">
        <nav class="space-y-1">
          <button
            v-for="section in sections"
            :key="section.id"
            @click="activeSection = section.id"
            :class="[
              'w-full flex items-center px-3 py-2 text-sm font-medium rounded-lg text-left transition-all duration-200',
              {
                'bg-primary-100 dark:bg-primary-900/20 text-primary-700 dark:text-primary-300': activeSection === section.id,
                'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-dark-800 hover:text-gray-900 dark:hover:text-gray-100': activeSection !== section.id
              }
            ]"
          >
            <component :is="section.icon" class="w-5 h-5 mr-3" />
            {{ section.name }}
          </button>
        </nav>
      </div>

      <!-- Content -->
      <div class="lg:col-span-2">
        <!-- Statistics Overview -->
        <div v-if="activeSection === 'overview'" class="card">
          <div class="p-6">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-6">
              使用统计概览
            </h2>

            <!-- Filter Controls -->
            <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
              <div class="flex items-center space-x-4">
                <select
                  v-model="dateRange"
                  @change="loadData"
                  class="px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                >
                  <option value="7">近7天</option>
                  <option value="30">近30天</option>
                  <option value="90">近90天</option>
                  <option value="all">全部</option>
                </select>
              </div>
            </div>

            <!-- Stats Cards -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
              <div class="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                <div class="flex items-center justify-between">
                  <div>
                    <p class="text-sm font-medium text-blue-600 dark:text-blue-400">总对话数</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-gray-100">{{ formatNumber(stats.totalSessions) }}</p>
                  </div>
                  <ChatBubbleOvalLeftEllipsisIcon class="w-8 h-8 text-blue-500" />
                </div>
              </div>

              <div class="p-4 bg-purple-50 dark:bg-purple-900/20 rounded-lg">
                <div class="flex items-center justify-between">
                  <div>
                    <p class="text-sm font-medium text-purple-600 dark:text-purple-400">总消息数</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-gray-100">{{ formatNumber(stats.totalMessages) }}</p>
                  </div>
                  <ChatBubbleLeftRightIcon class="w-8 h-8 text-purple-500" />
                </div>
              </div>

              <div class="p-4 bg-amber-50 dark:bg-amber-900/20 rounded-lg">
                <div class="flex items-center justify-between">
                  <div>
                    <p class="text-sm font-medium text-amber-600 dark:text-amber-400">Token使用</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-gray-100">{{ formatNumber(stats.totalTokens) }}</p>
                  </div>
                  <CpuChipIcon class="w-8 h-8 text-amber-500" />
                </div>
              </div>

              <div class="p-4 bg-emerald-50 dark:bg-emerald-900/20 rounded-lg">
                <div class="flex items-center justify-between">
                  <div>
                    <p class="text-sm font-medium text-emerald-600 dark:text-emerald-400">估算费用</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-gray-100">¥{{ formatCurrency(stats.totalCost) }}</p>
                  </div>
                  <CurrencyDollarIcon class="w-8 h-8 text-emerald-500" />
                </div>
              </div>
            </div>

            <!-- Charts -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div class="p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
                <h3 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-4">每日使用趋势</h3>
                <div class="h-64 flex items-center justify-center">
                  <div v-if="loading" class="text-center">
                    <div class="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-2"></div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">加载中...</p>
                  </div>
                  <div v-else-if="!dailyUsage.length" class="text-center">
                    <p class="text-gray-500 dark:text-gray-400">暂无数据</p>
                  </div>
                  <canvas v-else ref="dailyChart" class="w-full h-full"></canvas>
                </div>
              </div>

              <div class="p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
                <h3 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-4">Token使用分布</h3>
                <div class="h-64 flex items-center justify-center">
                  <div v-if="loading" class="text-center">
                    <div class="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-2"></div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">分析中...</p>
                  </div>
                  <div v-else-if="!dailyUsage.length" class="text-center">
                    <p class="text-gray-500 dark:text-gray-400">暂无数据</p>
                  </div>
                  <canvas v-else ref="tokenChart" class="w-full h-full"></canvas>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Chat History -->
        <div v-if="activeSection === 'history'" class="card">
          <div class="p-6">
            <div class="flex items-center justify-between mb-6">
              <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100">
                对话记录
              </h2>
              
              <!-- Search -->
              <div class="relative">
                <input
                  v-model="searchQuery"
                  type="text"
                  placeholder="搜索对话内容..."
                  class="w-64 px-4 py-2 pl-10 text-sm bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                />
                <MagnifyingGlassIcon class="w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2" />
                <button 
                  v-if="searchQuery"
                  @click="searchQuery = ''" 
                  class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                  <XMarkIcon class="w-4 h-4" />
                </button>
              </div>
            </div>

            <!-- Table -->
            <div class="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
              <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-800">
                  <tr>
                    <th class="text-left py-3 px-4 font-medium text-gray-700 dark:text-gray-300 text-sm">对话标题</th>
                    <th class="text-left py-3 px-4 font-medium text-gray-700 dark:text-gray-300 text-sm">创建时间</th>
                    <th class="text-left py-3 px-4 font-medium text-gray-700 dark:text-gray-300 text-sm">消息数</th>
                    <th class="text-left py-3 px-4 font-medium text-gray-700 dark:text-gray-300 text-sm">Token使用</th>
                    <th class="text-left py-3 px-4 font-medium text-gray-700 dark:text-gray-300 text-sm">操作</th>
                  </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                  <tr
                    v-for="session in filteredSessions"
                    :key="session.id"
                    class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                  >
                    <td class="py-4 px-4 bg-gray-50 dark:bg-gray-800">
                      <div class="flex items-center space-x-3">
                        <div class="w-8 h-8 bg-primary-100 dark:bg-primary-900/20 rounded-lg flex items-center justify-center">
                          <ChatBubbleOvalLeftEllipsisIcon class="w-4 h-4 text-primary-600 dark:text-primary-400" />
                        </div>
                        <div>
                          <p class="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
                            {{ session.title }}
                          </p>
                          <p class="text-xs text-gray-500 dark:text-gray-400">
                            最后更新：{{ formatTime(session.updated_at) }}
                          </p>
                        </div>
                      </div>
                    </td>
                    <td class="py-4 px-4 text-sm text-gray-600 dark:text-gray-400">
                      {{ formatDateTime(session.created_at) }}
                    </td>
                    <td class="py-4 px-4">
                      <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-300">
                        {{ session.message_count }}
                      </span>
                    </td>
                    <td class="py-4 px-4">
                      <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-300">
                        {{ formatNumber(session.token_usage) }}
                      </span>
                    </td>
                    <td class="py-4 px-4">
                      <div class="flex items-center space-x-2">
                        <button
                          @click="viewSession(session)"
                          class="p-2 text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
                          title="查看详情"
                        >
                          <EyeIcon class="w-4 h-4" />
                        </button>
                        <button
                          @click="exportSession(session)"
                          class="p-2 text-gray-400 hover:text-green-600 dark:hover:text-green-400 transition-colors rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
                          title="导出对话"
                        >
                          <ArrowDownTrayIcon class="w-4 h-4" />
                        </button>
                        <button
                          @click="deleteSession(session)"
                          class="p-2 text-gray-400 hover:text-red-600 dark:hover:text-red-400 transition-colors rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
                          title="删除对话"
                        >
                          <TrashIcon class="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>

              <!-- Empty state -->
              <div v-if="!loading && !filteredSessions.length" class="text-center py-12">
                <ChatBubbleOvalLeftEllipsisIcon class="w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-4" />
                <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">
                  {{ searchQuery ? '未找到匹配的对话' : '还没有对话记录' }}
                </h3>
                <p class="text-gray-500 dark:text-gray-400 mb-4">
                  {{ searchQuery ? '尝试调整搜索关键词' : '开始与AI助手对话吧' }}
                </p>
                <button 
                  v-if="searchQuery"
                  @click="searchQuery = ''"
                  class="btn-primary text-sm"
                >
                  清空搜索
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Session Detail Modal -->
    <div
      v-if="selectedSession"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
      @click.self="selectedSession = null"
    >
      <div class="bg-white dark:bg-dark-800 rounded-lg max-w-4xl w-full max-h-[80vh] overflow-hidden">
        <div class="flex items-center justify-between p-6 border-b border-gray-200 dark:border-dark-700">
          <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">
            {{ selectedSession.title }}
          </h3>
          <button
            @click="selectedSession = null"
            class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-dark-700"
          >
            <XMarkIcon class="w-5 h-5" />
          </button>
        </div>
        
        <div class="p-6 overflow-y-auto max-h-[60vh]">
          <div v-if="sessionMessages.length === 0" class="text-center py-8">
            <p class="text-gray-500 dark:text-gray-400">加载对话内容中...</p>
          </div>
          
          <div v-else class="space-y-4">
            <div
              v-for="message in sessionMessages"
              :key="message.id"
              :class="[
                'p-4 rounded-lg',
                message.role === 'user' ? 
                  'bg-primary-50 dark:bg-primary-900/20 ml-8' : 
                  'bg-gray-50 dark:bg-dark-700 mr-8'
              ]"
            >
              <div class="flex items-start space-x-3">
                <div :class="[
                  'w-8 h-8 rounded-full flex items-center justify-center text-xs font-medium',
                  message.role === 'user' ? 
                    'bg-primary-500 text-white' : 
                    'bg-gray-500 text-white'
                ]">
                  {{ message.role === 'user' ? 'U' : 'AI' }}
                </div>
                <div class="flex-1 min-w-0">
                  <p class="text-sm text-gray-900 dark:text-gray-100 whitespace-pre-wrap">
                    {{ message.content }}
                  </p>
                  <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">
                    {{ formatDateTime(message.timestamp) }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useChatStore } from '@/store/chat'
import { useAppStore } from '@/store/app'
import { aiAPI } from '@/api'
import type { ChatSession, ChatMessage } from '@/types'
import { formatDistanceToNow, format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { Chart, registerables } from 'chart.js'

Chart.register(...registerables)

// Icons
import {
  ChatBubbleOvalLeftEllipsisIcon,
  ChatBubbleLeftRightIcon,
  CpuChipIcon,
  CurrencyDollarIcon,
  ArrowDownTrayIcon,
  MagnifyingGlassIcon,
  EyeIcon,
  TrashIcon,
  XMarkIcon,
  ChartBarIcon
} from '@heroicons/vue/24/outline'

const chatStore = useChatStore()
const appStore = useAppStore()

// Refs
const dailyChart = ref<HTMLCanvasElement>()
const tokenChart = ref<HTMLCanvasElement>()

// State
const loading = ref(false)
const dateRange = ref('30')
const searchQuery = ref('')
const activeSection = ref('overview')
const selectedSession = ref<ChatSession | null>(null)
const sessionMessages = ref<ChatMessage[]>([])

const stats = ref({
  totalSessions: 0,
  totalMessages: 0,
  totalTokens: 0,
  totalCost: 0,
  averageTokensPerSession: 0
})

const dailyUsage = ref<Array<{
  date: string
  tokens: number
  cost: number
  messages: number
}>>([])

// Sections
const sections = [
  { id: 'overview', name: '统计概览', icon: ChartBarIcon },
  { id: 'history', name: '对话记录', icon: ChatBubbleOvalLeftEllipsisIcon }
]

// Computed
const filteredSessions = computed(() => {
  return chatStore.sessions.filter(session => {
    if (!searchQuery.value) return true
    return session.title.toLowerCase().includes(searchQuery.value.toLowerCase())
  })
})

// Methods
const loadData = async () => {
  loading.value = true
  try {
    const days = dateRange.value === 'all' ? 365 : parseInt(dateRange.value)
    
    // 并行加载统计数据
    const statsResponse = await aiAPI.getStats(days)

    // 处理统计数据
    if (statsResponse.success && statsResponse.data) {
      const { total_stats, daily_stats } = statsResponse.data
      
      stats.value = {
        totalSessions: total_stats.total_sessions,
        totalMessages: total_stats.total_messages,
        totalTokens: total_stats.total_tokens,
        totalCost: total_stats.estimated_cost,
        averageTokensPerSession: total_stats.total_sessions > 0 ? 
          Math.round(total_stats.total_tokens / total_stats.total_sessions) : 0
      }
      
      dailyUsage.value = daily_stats.map(item => ({
        date: item.date,
        tokens: item.total_tokens,
        cost: item.total_tokens * 0.000014, // 估算费用
        messages: item.message_count
      }))
    }

    // 加载对话列表
    await chatStore.loadSessions()
    
  } catch (error) {
    console.error('加载数据失败:', error)
    appStore.showError('加载数据失败')
  } finally {
    loading.value = false
  }
}

const formatNumber = (num: number) => {
  return new Intl.NumberFormat('zh-CN').format(num)
}

const formatCurrency = (amount: number) => {
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 4
  }).format(amount)
}

const formatTime = (date: string | Date) => {
  if (!date) return ''
  return formatDistanceToNow(new Date(date), { 
    addSuffix: true,
    locale: zhCN
  })
}

const formatDateTime = (date: string | Date) => {
  if (!date) return ''
  return format(new Date(date), 'yyyy-MM-dd HH:mm', { locale: zhCN })
}

// Chart functions
const renderDailyChart = () => {
  if (!dailyChart.value || !dailyUsage.value.length) return
  
  const ctx = dailyChart.value.getContext('2d')
  if (!ctx) return
  
  new Chart(ctx, {
    type: 'line',
    data: {
      labels: dailyUsage.value.map(d => format(new Date(d.date), 'MM-dd')),
      datasets: [
        {
          label: 'Token使用量',
          data: dailyUsage.value.map(d => d.tokens),
          borderColor: '#0ea5e9',
          backgroundColor: 'rgba(14, 165, 233, 0.1)',
          tension: 0.4,
          fill: true
        },
        {
          label: '消息数量',
          data: dailyUsage.value.map(d => d.messages),
          borderColor: '#10b981',
          backgroundColor: 'rgba(16, 185, 129, 0.1)',
          tension: 0.4,
          yAxisID: 'y1'
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          type: 'linear',
          display: true,
          position: 'left',
        },
        y1: {
          type: 'linear',
          display: true,
          position: 'right',
          grid: {
            drawOnChartArea: false,
          },
        },
      },
      plugins: {
        legend: {
          display: true,
          position: 'top'
        }
      }
    }
  })
}

const renderTokenChart = () => {
  if (!tokenChart.value || !dailyUsage.value.length) return
  
  const ctx = tokenChart.value.getContext('2d')
  if (!ctx) return
  
  const totalTokens = stats.value.totalTokens
  const last7Days = dailyUsage.value.slice(-7)
  const last30Days = dailyUsage.value.slice(-30)
  
  new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['最近7天', '7-30天前', '30天前'],
      datasets: [{
        data: [
          last7Days.reduce((sum, d) => sum + d.tokens, 0),
          last30Days.slice(0, -7).reduce((sum, d) => sum + d.tokens, 0),
          totalTokens - last30Days.reduce((sum, d) => sum + d.tokens, 0)
        ],
        backgroundColor: [
          '#0ea5e9',
          '#10b981',
          '#f59e0b'
        ],
        borderWidth: 0
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: true,
          position: 'bottom'
        }
      }
    }
  })
}

const viewSession = async (session: ChatSession) => {
  selectedSession.value = session
  
  try {
    await chatStore.loadSessionMessages(session.id)
    sessionMessages.value = chatStore.messages.filter(m => m.session_id === session.id)
  } catch (error) {
    appStore.showError('加载对话详情失败')
  }
}

const exportSession = async (session: ChatSession) => {
  try {
    // Load session messages
    await chatStore.loadSessionMessages(session.id)
    const messages = chatStore.messages.filter(m => m.session_id === session.id)
    
    // Create export content
    const content = [
      `对话标题: ${session.title}`,
      `创建时间: ${formatDateTime(session.created_at)}`,
      `消息数量: ${session.message_count}`,
      `Token使用: ${session.token_usage}`,
      '',
      '=== 对话内容 ===',
      ''
    ]
    
    messages.forEach(message => {
      content.push(`[${message.role.toUpperCase()}] ${formatDateTime(message.timestamp)}`)
      content.push(message.content)
      content.push('')
    })
    
    // Download file
    const blob = new Blob([content.join('\n')], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `对话导出_${session.title}_${format(new Date(), 'yyyyMMdd_HHmmss')}.txt`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    appStore.showSuccess('对话已导出')
  } catch (error) {
    appStore.showError('导出失败')
  }
}

const deleteSession = async (session: ChatSession) => {
  if (!confirm(`确定要删除对话"${session.title}"吗？此操作不可撤销。`)) {
    return
  }
  
  try {
    await chatStore.deleteSession(session.id)
    appStore.showSuccess('对话已删除')
    await loadData() // Refresh data
  } catch (error) {
    appStore.showError('删除失败')
  }
}

// Watchers
watch([dailyUsage, activeSection], () => {
  if (activeSection.value === 'overview') {
    nextTick(() => {
      renderDailyChart()
      renderTokenChart()
    })
  }
})

// Lifecycle
onMounted(async () => {
  await loadData()
})
</script>